package com.gitee.chili.leisure.api.room;

import com.gitee.chili.leisure.ResponseResult;
import com.gitee.chili.leisure.annotation.PathRestController;
import com.gitee.chili.leisure.domain.EntryRoom;
import com.gitee.chili.leisure.domain.GamesMode;
import com.gitee.chili.leisure.domain.Room;
import com.gitee.chili.leisure.domain.dto.EntryRoomQuery;
import com.gitee.chili.leisure.game.RoomDetail;
import com.gitee.chili.leisure.service.IGameTypeService;
import com.gitee.chili.leisure.service.IRoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * RoomController
 *
 * @author week solider
 * @since 2020.09.04
 */
@Validated
@PathRestController("/room")
public class RoomController {

    @Autowired
    private IRoomService roomService;

    @Autowired
    private IGameTypeService gameTypeService;

    @PostMapping("/createFriendRoom")
    public ResponseResult<RoomDetail> createFriendRoom(@Valid Room room) {

        // 创建房间
        Room save = roomService.save(room);

        if (Objects.isNull(save)) {
            return ResponseResult.failure("创建房间失败");
        }

        RoomDetail roomDetail = roomService.createRoom(save);

        return ResponseResult.success(roomDetail);
    }

    @PostMapping("/entry")
    public ResponseResult<EntryRoom> entryRoom(@Valid EntryRoomQuery query) {

        roomService.entryRoom(query);

        return ResponseResult.success();

    }

    @PostMapping("/getType")
    public ResponseResult<GamesMode> getType(Long id) {

        Optional<GamesMode> optional = gameTypeService.findById(id);
        if (optional.isPresent()) {
            return ResponseResult.success(optional.get());
        }
        return ResponseResult.failure("查询失败");
    }

    @PostMapping("/getChildren")
    public ResponseResult<List<GamesMode>> getChildren(Long id) {

        List<GamesMode> children = gameTypeService.getChildren(id);

        return ResponseResult.success(children);
    }

    @PostMapping("/leave")
    public ResponseResult<EntryRoom> leaveRoom(Long roomNum, Long memberId){

        roomService.leaveRoom(roomNum, memberId);

        return ResponseResult.success();

    }

    @PostMapping("/dissolved")
    public ResponseResult<Room> dissolved(Long roomNum){
        roomService.dissolved(roomNum);

        return ResponseResult.success();
    }

}
